<!--
 * @Author: 规格/数量操作弹框
 * @Date: 2025-09-07 18:00:00
 * @LastEditors: xiaodi 53527718@qq.com
 * @LastEditTime: 2025-10-12 00:03:05
 * @Description: 修改菜品规格和数量的弹框组件
-->

<template>
  <CustomDialog
    v-model:visible="dialogVisible"
    top="8vh"
    curent-class="specification-quantity-dialog"
  >
    <div class="specification-quantity-container">
      <!-- 标题 -->
      <div class="title">
        <span v-if="currentFoodData?.spec_type === 20">数量/规格</span>
        <span v-else>数量</span>
      </div>

      <!-- 内容区域 -->
      <div class="content-box">
        <!-- 左侧：菜品信息和规格选择 -->
        <div class="left-box">
          <div class="food-info">
            <!-- 菜品图片和名称 -->
            <div class="food-image-name">
              <img
                class="food-image"
                :src="
                  currentFoodData.image_url !== ''
                    ? currentFoodData.image_url
                    : '@/assets/images/home/not-goodimage.png'
                "
                alt="菜品图片"
                v-if="currentFoodData?.image_url"
              />
              <span class="food-name">{{ currentFoodData?.name }}</span>
            </div>

            <!-- 多规格选择 -->
            <template v-if="currentFoodData?.spec_type === 20">
              <div class="spec-title">菜品规格</div>
              <div class="spec-list">
                <div
                  class="spec-item"
                  v-for="(item, index) in currentFoodData.skuList"
                  :key="item.id + index"
                >
                  <div
                    class="spec-option"
                    :class="{ 'spec-option-active': skuActiveIndex === index }"
                    @click="handleSelectSpec(index, item)"
                    v-for="sku in item.food_props"
                    :key="sku.value.id"
                  >
                    <span class="spec-name">{{ sku.value.name }}</span>
                    <div class="spec-price">
                      <span v-if="isVipPrice">￥{{ item.member_price }}/份</span>
                      <span v-else>￥{{ item.price }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>

        <!-- 分割线 -->
        <div class="divider"></div>

        <!-- 右侧：数量输入和数字键盘 -->
        <div class="right-box">
          <div class="quantity-input-box">
            <div class="input-row">
              <span class="input-label">数量</span>
              <div class="input-container">
                <input
                  class="quantity-input"
                  v-model.trim="quantityValue"
                  type="text"
                  placeholder="请输入数量"
                  style="width: 2.4rem"
                />
                <img
                  class="clear-icon"
                  @click="handleClearInput"
                  v-show="quantityValue"
                  src="@/assets/images/home/input-clear.png"
                  alt="清除"
                />
              </div>
            </div>
          </div>

          <!-- 数字键盘 -->
          <NumberKeyboard
            v-model:keyword="quantityValue"
            :loading="loading"
            @onInputKeyboard="onInputKeyboard"
            @onCancel="handleClearInput"
            @onConfirm="handleSubmit"
          />
        </div>
      </div>
    </div>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'
import { useUserStore } from '@/stores/user'

interface Props {
  modelValue: boolean
  currentFoodData?: any
  loading?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
  (e: 'confirm', payload: { num: number; food_sku_id?: any }): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  currentFoodData: null,
  loading: false
})

const emit = defineEmits<Emits>()

const userStore = useUserStore()

// 弹框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 选中的规格索引
const skuActiveIndex = ref(-1)
// 数量输入值
const quantityValue = ref('')
// 选中的规格数据
const skuActiveData = ref<any>({})
// 仅回显使用，不在组件内拉取

// 是否显示会员价
const isVipPrice = computed(() => {
  return userStore.shopInfo?.is_vip_price === 1
})

// 监听弹框显示状态
watch(
  () => props.modelValue,
  newVal => {
    if (newVal) initDialog()
    else resetData()
  }
)

// 初始化弹框数据
const initDialog = () => {
  const data = props.currentFoodData
  if (!data) return
  // 使用父层准备好的数据进行回显
  quantityValue.value = String(data.num || 1)
  if (data.spec_type === 20) {
    const currentSkuId = data.skuInfo?.food_sku_id
    if (currentSkuId) {
      data.skuList?.forEach((item: any, index: number) => {
        if (item.food_sku_id === currentSkuId || item.id === currentSkuId) {
          skuActiveIndex.value = index
          skuActiveData.value = {
            ...data,
            food_sku_id: item.food_sku_id ?? item.id,
            foodPrice: item.price,
            memberPrice: item.member_price,
            foodUnit: item.unit
          }
        }
      })
    }
  }
}

// 不在组件内拉取数据

// 选择规格
const handleSelectSpec = (index: number, item: any) => {
  skuActiveIndex.value = index
  // 切换规格时清空数量
  quantityValue.value = ''

  skuActiveData.value = {
    ...props.currentFoodData,
    food_sku_id: item.id,
    foodPrice: item.price,
    memberPrice: item.member_price,
    foodUnit: item.unit
  }
}

// 清空输入
const handleClearInput = () => {
  quantityValue.value = ''
}

// 数字键盘输入
const onInputKeyboard = (val: string) => {
  quantityValue.value = val
}

// 提交（仅校验并向外抛出数据，不调用后端）
const handleSubmit = async () => {
  debugger
  // 多规格需要选择规格
  if (props.currentFoodData?.spec_type === 20 && skuActiveIndex.value === -1) {
    ElMessage.warning('请选择对应的规格')
    return
  }

  // 数量不能为空
  if (!quantityValue.value) {
    ElMessage.warning('请输入数量')
    return
  }

  // 数量验证

  const num = props.currentFoodData?.is_weight !== 0 ? Number(quantityValue.value) : parseInt(quantityValue.value)
  if (isNaN(num) || num <= 0) {
    ElMessage.warning('请输入有效的数量')
    return
  }
  let food_sku_id = null
  if (
    props.currentFoodData?.spec_type === 20 &&
    skuActiveData.value?.food_sku_id !== props.currentFoodData?.skuInfo?.food_sku_id
  ) {
    food_sku_id = skuActiveData.value?.food_sku_id
  }
  // 抛出事件由父级决定如何提交
  emit('confirm', { num, food_sku_id })
}

// 重置数据
const resetData = () => {
  skuActiveIndex.value = -1
  quantityValue.value = ''
  skuActiveData.value = {}
  skuActiveData.value = {}
}
</script>

<style scoped lang="scss">
.specification-quantity-container {
  width: 984px;
  height: 394px;
  box-sizing: border-box;
}

.title {
  font-size: 20px;
  font-family:
    PingFang SC,
    PingFang SC-Bold;
  font-weight: 700;
  color: #333333;
  text-align: left;
  margin-bottom: 20px;
}

.content-box {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  height: 100%;
  box-sizing: border-box;
}

.left-box {
  width: 408px;
  box-sizing: border-box;
}

.food-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.food-image-name {
  display: flex;
  align-items: flex-start;
  gap: 23px;

  .food-image {
    width: 133px;
    height: 133px;
    object-fit: cover;
    border-radius: 8px;
  }

  .food-name {
    font-size: 18px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    color: #333333;
    margin-top: 16px;
    line-height: 1.4;
  }
}

.spec-title {
  font-size: 16px;
  font-family:
    PingFang SC,
    PingFang SC-Bold;
  font-weight: 700;
  color: #333333;
  margin-bottom: 10px;
}

.spec-list {
  max-height: 200px;
  overflow-y: auto;

  .spec-item {
    margin-bottom: 10px;

    .spec-option {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      background: #ffffff;
      border: 1px solid #d0d0d0;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #7c0a03;
      }

      &.spec-option-active {
        background: #7c0a03;
        border-color: #7c0a03;
        color: #ffffff;

        .spec-name {
          color: #ffffff;
        }

        .spec-price {
          color: #ffffff;
        }
      }

      .spec-name {
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
      }

      .spec-price {
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #7c0a03;
      }
    }
  }
}

.divider {
  width: 1px;
  height: 100%;
  background: #d0d0d0;
  margin: 0 20px;
}

.right-box {
  width: 516px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.quantity-input-box {
  .input-row {
    display: flex;
    align-items: center;
    gap: 18px;

    .input-label {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
      min-width: 40px;
    }

    .input-container {
      position: relative;
      display: flex;
      align-items: center;

      .quantity-input {
        width: 200px;
        height: 40px;
        padding: 0 40px 0 12px;
        border: 1px solid #d0d0d0;
        border-radius: 8px;
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
        background: #ffffff;
        box-sizing: border-box;

        &:focus {
          outline: none;
          border-color: #7c0a03;
        }

        &::placeholder {
          color: #999999;
        }
      }

      .clear-icon {
        position: absolute;
        right: 12px;
        width: 16px;
        height: 16px;
        cursor: pointer;
      }
    }
  }
}

// 滚动条样式
.spec-list::-webkit-scrollbar {
  width: 6px;
}

.spec-list::-webkit-scrollbar-thumb {
  background: #d2d2d2;
  border-radius: 3px;
}

.spec-list::-webkit-scrollbar-track {
  background: #f4f4f4;
  border-radius: 3px;
}
</style>
